/* 面试题 01.05. 一次编辑 */
/**
 * @param {string} first
 * @param {string} second
 * @return {boolean}
 */
/* 暴力 */
var oneEditAway = function (first, second) {
	const fLen = first.length,
		sLen = second.length
	const maxLen = Math.max(fLen, sLen)
	if (Math.abs(fLen - sLen) > 1) return false
	if (first === second) return true
	for (let i = 0; i < maxLen; i++) {
		if (first[i] !== second[i]) {
			if (fLen === sLen) {
				/* 替换只能相同长度 */
				const fNext = first.slice(i + 1)
				const sNext = second.slice(i + 1)
				if (fNext === sNext) return true
				return false
			}
			/* 插入或者截取 */
			if (!i) {
				if (fLen > sLen) {
					const fNext = first.slice(i + 1)
					if (fNext === second) return true
				} else {
					const sNext = first.slice(i + 1)
					if (first === sNext) return true
				}
				return false
			} else {
				if (fLen > sLen) {
					const fNext = first.slice(i + 1)
					const sNext = second.slice(i)
					if (fNext === sNext) return true
				} else {
					const fNext = first.slice(i)
					const sNext = second.slice(i + 1)
					if (fNext === sNext) return true
				}
				return false
			}
		}
	}
	return false
}

/* 分情况讨论 */
var oneEditAway = function (first, second) {
	const m = first.length,
		n = second.length
	const oneInsert = (shorter, longer) => {
		const length1 = shorter.length,
			length2 = longer.length

		let index1 = 0,
			index2 = 0
		while (index1 < length1 && index2 < length2) {
			if (shorter[index1] === longer[index2]) {
				index1++
			}
			index2++
			if (index2 - index1 > 1) return false
		}
		return true
	}
	if (n - m === 1) {
		return oneInsert(first, second)
	} else if (m - n === 1) {
		return oneInsert(second, first)
	} else if (m === n) {
		let foundDifference = false
		for (let i = 0; i < m; i++) {
			if (first[i] !== second[i]) {
				if (!foundDifference) {
					foundDifference = true
				} else {
					return false
				}
			}
		}
		return true
	}
	return false
}
const result = oneEditAway('a', 'ab')
console.log('oneEditAway :>>', result)
